package com.zw.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zw.dao.CommodityMapper;
import com.zw.dao.OrderMapper;
import com.zw.entity.Commodity;
import com.zw.entity.CommodityExample;
import com.zw.entity.Order;
import com.zw.entity.OrderExample;
import com.zw.service.OrderService;

@Service
public class OrderServiceImpl implements OrderService{

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private CommodityMapper commodityMapper;
	
	@Override
	@Transactional
	public int insertOrder(Order o) {
		CommodityExample cExample=new CommodityExample();
		cExample.or().andCommodityidEqualTo(o.getCommodityid());
		Commodity commodity=commodityMapper.selectCommodity(cExample);
		if(o.getCommoditycount()<=commodity.getCommoditycount()){
			int count=commodity.getCommoditycount()-o.getCommoditycount();
			commodity.setCommoditycount(count);
			cExample=new CommodityExample();
			cExample.or().andCommodityidEqualTo(o.getCommodityid());
			int num=commodityMapper.updateByExample(commodity, cExample);
			if(num<0){
				return -1;
			}
			o.setOrderdate(new Date());
			o.setOrderstate(1);
			o.setOrderid(null);
			num=orderMapper.insert(o);
			if(num<0){
				return -1;
			}
		}
		return 1;
	}

	@Override
	public Order selectOrder(int oId) {
		return orderMapper.selectByPrimaryKey(oId);
	}

	@Override
	public List<Order> selectOrderAll(int userid) {
		OrderExample orderExample=new OrderExample();
		orderExample.or().andUseridEqualTo(userid).andOrderstateEqualTo(1);
		return orderMapper.selectByExample(orderExample);
	}

	@Override
	public int updateOrder(Order order) {
		return 	orderMapper.updateByPrimaryKey(order);
	}

}
